﻿using Dm.util;
using System;
using System.Buffers.Binary;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Windows.Threading;
using 凯蒽斯.Dto;
using 凯蒽斯.Help;

namespace 凯蒽斯.page
{
    /// <summary>
    /// AxisSettingControl.xaml 的交互逻辑
    /// </summary>
    public partial class AxisSettingControl : UserControl
    {
        private readonly DispatcherTimer _timer = new DispatcherTimer();

        public AxisSettingControl()
        {
            InitializeComponent();
            _timer.Interval = TimeSpan.FromSeconds(1);
            // 绑定定时器触发事件（循环读取的核心）
            _timer.Tick += async (s, e) => await Timer_TickAsync();
            _timer.Start();
        }

        private async Task Timer_TickAsync()
        {
            // 处理“点动速度”
            if (MainWindow.valuePairs.TryGetValue("Ghb_点动速度", out object Ghb_JOG)  // 确保键存在
                && Ghb_JOG is double[] sourceArray  // 确保类型是Int64数组
                && sourceArray.Length > 0)  // 确保数组有元素
            {
                int dotIndex = (sourceArray[0]).ToString().IndexOf('.');
                if (sourceArray[0].ToString().Length > 3)
                {

                    Ghb_点动速度.Text = (sourceArray[0]).ToString().Substring(0, dotIndex + 3);
                }
                else
                {
                    Ghb_点动速度.Text = (sourceArray[0]).ToString();
                }
            }
            else
            {
                Ghb_点动速度.Text = "点动速度数据无效";  // 异常处理，避免崩溃
            }

            // 处理“运行速度”
            if (MainWindow.valuePairs.TryGetValue("Ghb_运行速度", out object Ghb_RUN)  // 确保键存在
                && Ghb_RUN is double[] source  // 确保类型是Int64数组
                && source.Length > 0)  // 确保数组有元素
            {
                int dotIndex = (source[0]).ToString().IndexOf('.');
                if (source[0].ToString().Length > 3)
                {

                    Ghb_运行速度.Text = (source[0]).ToString().Substring(0, dotIndex + 3);

                }
                else
                {
                    Ghb_运行速度.Text = (source[0]).ToString();
                }
            }
            if (MainWindow.valuePairs.TryGetValue("Ghb_左摆位置", out object Axis1LeftPosition1)  // 确保键存在
                && Axis1LeftPosition1 is double[] Axis1LeftPositionValue  // 确保类型是Int64数组
                && Axis1LeftPositionValue.Length > 0)
            {
                for (int i = 0; i < Axis1LeftPositionValue.Length; i++)
                {
                    int dotIndex = Axis1LeftPositionValue[i].ToString().IndexOf('.');
                    if ((Axis1LeftPositionValue[i].ToString().Length > 3)
                        && (Convert.ToInt32(Axis1Show.Text) == i))
                    {
                        Axis1LeftPosition.Text = Axis1LeftPositionValue[i].ToString().substring(0, (i + 3));
                    }
                    else if (Convert.ToInt32(Axis1Show.Text) == i)
                    {
                        Axis1LeftPosition.Text = Axis1LeftPositionValue[i].ToString();
                    }
                    if ((Axis1LeftPositionValue[i].ToString().Length > 3)
                        && (Convert.ToInt32(Axis2Show.Text) == i))
                    {
                        Axis2LeftPosition.Text = Axis1LeftPositionValue[i].ToString().substring(0, (i + 3));
                    }
                    else if (Convert.ToInt32(Axis2Show.Text) == i)
                    {
                        Axis2LeftPosition.Text = Axis1LeftPositionValue[i].ToString();
                    }
                    if ((Axis1LeftPositionValue[i].ToString().Length > 3)
                        && (Convert.ToInt32(Axis3Show.Text) == i))
                    {
                        Axis3LeftPosition.Text = Axis1LeftPositionValue[i].ToString().substring(0, (i + 3));
                    }
                    else if (Convert.ToInt32(Axis3Show.Text) == i)
                    {
                        Axis3LeftPosition.Text = Axis1LeftPositionValue[i].ToString();
                    }
                }
                
            }
            if (MainWindow.valuePairs.TryGetValue("Ghb_中摆位置", out object AxisMiddlePosition)  // 确保键存在
                && AxisMiddlePosition is double[] AxisMiddlePositionDouble  // 确保类型是Int64数组
                && AxisMiddlePositionDouble.Length > 0)
            {
                for (int i = 0; i < AxisMiddlePositionDouble.Length; i++)
                {
                    int dotIndex = AxisMiddlePositionDouble[i].ToString().IndexOf('.');
                    if ((AxisMiddlePositionDouble[i].ToString().Length > 3)
                        && (Convert.ToInt32(Axis1Show.Text) == i))
                    {
                        Axis1MiddlePosition.Text = AxisMiddlePositionDouble[i].ToString().substring(0, (i + 3));
                    }
                    else if (Convert.ToInt32(Axis1Show.Text) == i)
                    {
                        Axis1MiddlePosition.Text = AxisMiddlePositionDouble[i].ToString();
                    }
                    if ((AxisMiddlePositionDouble[i].ToString().Length > 3)
                        && (Convert.ToInt32(Axis2Show.Text) == i))
                    {
                        Axis2MiddlePosition.Text = AxisMiddlePositionDouble[i].ToString().substring(0, (i + 3));
                    }
                    else if (Convert.ToInt32(Axis2Show.Text) == i)
                    {
                        Axis2MiddlePosition.Text = AxisMiddlePositionDouble[i].ToString();
                    }
                    if ((AxisMiddlePositionDouble[i].ToString().Length > 3)
                        && (Convert.ToInt32(Axis3Show.Text) == i))
                    {
                        Axis3MiddlePosition.Text = AxisMiddlePositionDouble[i].ToString().substring(0, (i + 3));
                    }
                    else if (Convert.ToInt32(Axis3Show.Text) == i)
                    {
                        Axis3MiddlePosition.Text = AxisMiddlePositionDouble[i].ToString();
                    }
                }
                if (MainWindow.valuePairs.TryGetValue("Ghb_右摆位置", out object AxisRightPosition)  // 确保键存在
            && AxisRightPosition is double[] AxisRightPositionValue  // 确保类型是Int64数组
            && AxisRightPositionValue.Length > 0)
                {
                    for (int i = 0; i < AxisRightPositionValue.Length; i++)
                    {
                        int dotIndex = AxisRightPositionValue[i].ToString().IndexOf('.');
                        if ((AxisRightPositionValue[i].ToString().Length > 3)
                            && (Convert.ToInt32(Axis1Show.Text) == i))
                        {
                            Axis1RightPosition.Text = AxisRightPositionValue[i].ToString().substring(0, (i + 3));
                        }
                        else if (Convert.ToInt32(Axis1Show.Text) == i)
                        {
                            Axis1RightPosition.Text = AxisRightPositionValue[i].ToString();
                        }
                        if ((AxisRightPositionValue[i].ToString().Length > 3)
                            && (Convert.ToInt32(Axis2Show.Text) == i))
                        {
                            Axis2RightPosition.Text = AxisRightPositionValue[i].ToString().substring(0, (i + 3));
                        }
                        else if (Convert.ToInt32(Axis2Show.Text) == i)
                        {
                            Axis2RightPosition.Text = AxisRightPositionValue[i].ToString();
                        }
                        if ((AxisRightPositionValue[i].ToString().Length > 3)
                            && (Convert.ToInt32(Axis3Show.Text) == i))
                        {
                            Axis3RightPosition.Text = AxisRightPositionValue[i].ToString().substring(0, (i + 3));
                        }
                        else if (Convert.ToInt32(Axis3Show.Text) == i)
                        {
                            Axis3RightPosition.Text = AxisRightPositionValue[i].ToString();
                        }
                    }
                }
            }
            if (MainWindow.valuePairs.TryGetValue("Ghr_当前位置", out object Axis1PlaceValue)  // 确保键存在
                && Axis1PlaceValue is double[] Axis1PlaceDouble  // 确保类型是Int64数组
                && Axis1PlaceDouble.Length > 0)
            {
                for (int i = 0; i < Axis1PlaceDouble.Length; i++)
                {
                    int dotIndex = Axis1PlaceDouble[i].ToString().IndexOf('.');
                    if ((Axis1PlaceDouble[i].ToString().Length > 3)
                        && (Convert.ToInt32(Axis1Show.Text) == i))
                    {
                        Axis1Place.Text = Axis1PlaceDouble[i].ToString().substring(0, (i + 3));
                    }
                    else if (Convert.ToInt32(Axis1Show.Text) == i)
                    {
                        Axis1Place.Text = Axis1PlaceDouble[i].ToString();
                    }
                    if ((Axis1PlaceDouble[i].ToString().Length > 3)
                        && (Convert.ToInt32(Axis2Show.Text) == i))
                    {
                        Axis2Place.Text = Axis1PlaceDouble[i].ToString().substring(0, (i + 3));
                    }
                    else if (Convert.ToInt32(Axis2Show.Text) == i)
                    {
                        Axis2Place.Text = Axis1PlaceDouble[i].ToString();
                    }
                    if ((Axis1PlaceDouble[i].ToString().Length > 3)
                        && (Convert.ToInt32(Axis3Show.Text) == i))
                    {
                        Axis3Place.Text = Axis1PlaceDouble[i].ToString().substring(0, (i + 3));
                    }
                    else if (Convert.ToInt32(Axis3Show.Text) == i)
                    {
                        Axis3Place.Text = Axis1PlaceDouble[i].ToString();
                    }
                }

            }
        }

        private void JOG速度_PreviewMouseDown(object sender, MouseButtonEventArgs e)
        {
            _timer.Stop();
        }

        private void JOG速度_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Enter)
            {
                UpdateModbusValue(Ghb_点动速度.Text, "Ghb_点动速度",null);
                e.Handled = true;
            }
        }

        private void Ghb_运行速度_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Enter)
            {
                UpdateModbusValue(Ghb_运行速度.Text, "Ghb_运行速度",null);
                e.Handled = true;
            }
        }

        private async void UpdateModbusValue(string textValue, string description, ushort? startAddress)
        {
            try
            {
                if (!float.TryParse(textValue, out float parsedValue))
                {
                    MessageBox.Show("请输入有效的数字");
                    return;
                }

                // 转换逻辑
                byte[] floatBytes = BitConverter.GetBytes(parsedValue);
                ushort[] ushortCollection = new ushort[floatBytes.Length / 2];
                for (int i = 0; i < ushortCollection.Length; i++)
                {
                    ushortCollection[i] = BitConverter.ToUInt16(floatBytes, i * 2);
                }

                var setting = MainWindow.modbusSettings.FirstOrDefault(X => X.Description == description);
                if (setting != null&&startAddress==null)
                {
                    await MainWindow.modbusHelp.WriteMultipleRegistersAsync(
                        (byte)setting.unitId,
                        (ushort)setting.startAddress,
                        ushortCollection
                    ).ConfigureAwait(true);

                    _timer.Start(); // 重新启动定时器
                }
                else if (setting != null && startAddress != null)
                {
                    // 处理可空类型并计算最终地址
                    int settingStart = setting.startAddress;
                    int addStart = startAddress ?? throw new ArgumentNullException("startAddress 不能为 null");
                    int totalAddress = settingStart + addStart;

                    if (totalAddress < 0 || totalAddress > ushort.MaxValue)
                    {
                        throw new OverflowException($"地址总和 {totalAddress} 超出 ushort 范围（0~65535）");
                    }

                    ushort finalAddress = (ushort)totalAddress;

                    // 调用方法
                    await MainWindow.modbusHelp.WriteMultipleRegistersAsync(
                        (byte)setting.unitId,
                        finalAddress,  // 使用转换后的 ushort
                        ushortCollection
                    ).ConfigureAwait(true);

                    _timer.Start();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"{description} 设置失败: {ex.Message}");
            }
        }

        private void Axis1LeftPosition_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Enter)
            {
                UpdateModbusValue(Axis1LeftPosition.Text, "Ghb_左摆位置", (ushort)(Convert.ToInt32(Axis1Show.Text)*2));
                e.Handled = true;
            }
        }

        private void Axis1LeftPosition_TextChanged(object sender, TextChangedEventArgs e)
        {

        }

        private void Axis2MiddlePosition_KeyDown(object sender, KeyEventArgs e)
        {

        }

        private void Axis2LeftPosition_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Enter)
            {
                UpdateModbusValue(Axis2LeftPosition.Text, "Ghb_左摆位置", (ushort)(Convert.ToInt32(Axis2Show.Text) * 2));
                e.Handled = true;
            }
        }

        private void Axis3LeftPosition_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Enter)
            {
                UpdateModbusValue(Axis3LeftPosition.Text, "Ghb_左摆位置", (ushort)(Convert.ToInt32(Axis3Show.Text) * 2));
                e.Handled = true;
            }
        }

        private void Axis1Place_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Enter)
            {
                UpdateModbusValue(Axis1Place.Text, "Ghr_当前位置", (ushort)(Convert.ToInt32(Axis1Show.Text) * 2));
                e.Handled = true;
            }
        }

        private void Axis2Place_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Enter)
            {
                UpdateModbusValue(Axis2Place.Text, "Ghr_当前位置", (ushort)(Convert.ToInt32(Axis2Show.Text) * 2));
                e.Handled = true;
            }
        }

        private void Axis3Place_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Enter)
            {
                UpdateModbusValue(Axis2Place.Text, "Ghr_当前位置", (ushort)(Convert.ToInt32(Axis3Show.Text) * 2));
                e.Handled = true;
            }
        }

        private void Axis2MiddlePosition_KeyDown_1(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Enter)
            {
                UpdateModbusValue(Axis2Place.Text, "Ghb_中摆位置", (ushort)(Convert.ToInt32(Axis2Show.Text) * 2));
                e.Handled = true;
            }
        }

        private void Axis3RightPosition_KeyDown(object sender, KeyEventArgs e)
        {

        }

        private void Axis1MiddlePosition_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Enter)
            {
                UpdateModbusValue(Axis1Place.Text, "Ghb_中摆位置", (ushort)(Convert.ToInt32(Axis1Show.Text) * 2));
                e.Handled = true;
            }
        }

        private void Axis3MiddlePosition_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Enter)
            {
                UpdateModbusValue(Axis3Place.Text, "Ghb_中摆位置", (ushort)(Convert.ToInt32(Axis3Show.Text) * 2));
                e.Handled = true;
            }
        }

        private void Axis1MiddlePosition_KeyDown_1(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Enter)
            {
                UpdateModbusValue(Axis1Place.Text, "Ghb_中摆位置", (ushort)(Convert.ToInt32(Axis1Show.Text) * 2));
                e.Handled = true;
            }
        }
    }
}
